package org.openwebtop.common.security;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.ServletActionContext;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;

import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.Interceptor;

public class SecurityInterceptor implements Interceptor {
	private static final long serialVersionUID = -8434734220240694653L;

	@Override
	public void init() {
	}

	@Override
	public void destroy() {
	}

	@Override
	public String intercept(ActionInvocation invocation) throws Exception {
		final SecurityContext securityContext = SecurityContextHolder.getContext();

		if (securityContext != null) {
			final Authentication authentication = securityContext.getAuthentication();

			if (authentication != null) {
				final HttpServletRequest request = ServletActionContext.getRequest();

				if (request != null) {
					request.setAttribute("userContext", authentication.getPrincipal());
				}
			}
		}

		return invocation.invoke();
	}

}
